package com.leesche.zcsp.node.web.controller.web.v2.inventory;

import com.leesche.zcsp.node.utils.UUIDGenerateUtil;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.utils.web.WebUtils;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.controller.web.v2.admin.WebAdminController;
import com.leesche.zcsp.node.web.model.PubDevGiftStock;
import com.leesche.zcsp.node.web.service.PubDevGiftStockService;
import com.leesche.zcsp.node.web.service.PubPlaceService;
import com.leesche.zcsp.node.web.service.impl.data.read.PubDevGiftStockDto;
import com.leesche.zcsp.node.web.service.impl.data.read.PubPlaceDto;
import com.leesche.zcsp.node.web.service.impl.data.read.QueryPubDevGiftStockCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.QueryPubPlaceCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * @author reid
 * @Created 16/12/14
 */
@Controller
@RequestMapping("/v2/inventory")
public class WebInventoryController extends WebAdminController {

    private final static Logger LOGGER = LoggerFactory.getLogger(WebInventoryController.class);

    private static final String SHOW_VIEW = "web/v2/inventory/showView";

    @Autowired
    private PubPlaceService placeService;
    @Autowired
    private PubDevGiftStockService giftStockService;


    /**
     * 礼品库存首页
     * @param model
     * @return
     */
    @RequestMapping("/showView")
    public String showView(Model model) {
//        goPlaceView(model);

        Long adminId = getAdminId();
        QueryPubPlaceCondition placeCondition = new QueryPubPlaceCondition();
        placeCondition.setAdminId(adminId);
        List<PubPlaceDto> placeList = placeService.findPubPlaceList(placeCondition);
        model.addAttribute("placeList", placeList);
        QueryPubDevGiftStockCondition condition = new QueryPubDevGiftStockCondition();
        Long placeId = 0L;
        if(placeList.size()>0){
            placeId = placeList.get(0).getPlaceid();
            condition.setAdminId(adminId);
            condition.setPlaceId(placeId);
            List<PubDevGiftStockDto> list = giftStockService.findListsByCondition(condition);
            model.addAttribute("giftList", list);
        }
        model.addAttribute("placeId", placeId);
        return SHOW_VIEW;
    }

    @RequestMapping("/{placeId}/placeView")
    public String showPlaceView(@PathVariable("placeId") Long placeId, Model model) {
        Long adminId = getAdminId();
        QueryPubPlaceCondition placeCondition = new QueryPubPlaceCondition();
        placeCondition.setAdminId(adminId);
        List<PubPlaceDto> placeList = placeService.findPubPlaceList(placeCondition);
        model.addAttribute("placeList", placeList);

        QueryPubDevGiftStockCondition condition = new QueryPubDevGiftStockCondition();
        condition.setAdminId(adminId);
        condition.setPlaceId(placeId);
        List<PubDevGiftStockDto> list = giftStockService.findListsByCondition(condition);
        model.addAttribute("giftList", list);
        return SHOW_VIEW;
    }

    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Map<String, Object> update(Long giftId, String giftName, Integer giftQty) {
        LOGGER.info("开始更新礼品库存......");
        try {
            PubDevGiftStock gift = giftStockService.selectByPrimaryKey(giftId);
            gift.setGiftname(giftName);
            gift.setGiftqty(giftQty);
//            gift.setGiftimgurl(giftImgUrl);
            giftStockService.updateByPrimaryKey(gift);
            LOGGER.info("成功更新礼品库存......");
            return WebResult.success().toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/{giftId}/updateGiftImg", method = RequestMethod.POST)
    public Map<String, Object> updateDeviceImg(@PathVariable("giftId") Long giftId,
                    @RequestParam(value = "imageFile", required = false) MultipartFile imageUploadFile){
        try {
            PubDevGiftStock gift = giftStockService.selectByPrimaryKey(giftId);
            if (gift != null){
                if(imageUploadFile.isEmpty()){
                    return WebResult.failure("请选择图片").toMap();
                }

                String fileName = imageUploadFile.getOriginalFilename();
                String extName = fileName.substring(fileName.lastIndexOf("."));

                if (!WebUtils.checkIsImage(extName)
                        && !imageUploadFile.getContentType().matches("image.*")) {
                    return WebResult.failure("上传的文件必须是图片!").toMap();
                }

                String hexString = WebUtils.getFileHexString(imageUploadFile.getInputStream());

                boolean flag = false;
                String[] magic = Constants.SYSTEM_IMAGE_MAGICNUMBER;
                for (int i = 0; i < magic.length; i++) {
                    if (magic[i].equals(hexString)) {
                        flag = true;
                        break;
                    }
                }

                if (flag == false) {
                    return WebResult.failure("上传的文件不是图片类型").toMap();
                }

                if (imageUploadFile.getSize() > Constants.SYSTEM_IMAGE_SIZE) {
                    return WebResult.failure("文件太大,不能超过" + Constants.SYSTEM_IMAGE_SIZE + "M").toMap();
                }

                String imagePath = SessionManager.getContext().getRealPath("").replace(Constants.SITE_NAME,
                        Constants.SYSTEM_TMAGE_DEVICE_GIFT_DIRECTORY);
                String imageName = UUIDGenerateUtil.generateUUID() + extName;

                File imageFile = new File(imagePath, imageName);

                if (!imageFile.exists()) {
                    imageFile.mkdirs();
                }

                imageUploadFile.transferTo(imageFile);

                gift.setGiftimgurl(SessionManager.getWebServerURL() + Constants.SYSTEM_TMAGE_DEVICE_GIFT_DIRECTORY + "/" + imageName);
                giftStockService.updateByPrimaryKey(gift);
                return WebResult.success().info("图片上传成功").put("data", gift.getGiftimgurl()).toMap();
            }
            return WebResult.failure("没有权限").toMap();
        }catch (Exception e){
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 查询所有场地
     * @param model
     * @return
     */
    private Model goPlaceView(Model model) {
        Long adminId = getAdminId();
        QueryPubPlaceCondition placeCondition = new QueryPubPlaceCondition();
        placeCondition.setAdminId(adminId);
        List<PubPlaceDto> placeList = placeService.findPubPlaceList(placeCondition);
        model.addAttribute("placeList", placeList);
        return model;
    }

}
